package com.jt.common.aspect;

import java.lang.reflect.Method;
import java.util.Date;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

//import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jt.common.annotation.RequestLog;
import com.jt.common.exception.ServiceException;
import com.jt.common.utils.IPUtils;
import com.jt.sys.dao.SysLogDao;
import com.jt.sys.entity.SysLog;

@Aspect
@Service
public class SysLogAspect {
	@Autowired
	private SysLogDao sysLogDao;
	@Pointcut("@annotation(com.jt.common.annotation.RequestLog)")
	public void logPointCut(){}
	
	@Around("logPointCut()")
	public Object around(ProceedingJoinPoint pj) throws Throwable{
		long beginTime = System.currentTimeMillis();
		Object result = pj.proceed();
		long time = System.currentTimeMillis()-beginTime;
		saveSysLog(pj,time);
		return result;
	}

	private void saveSysLog(ProceedingJoinPoint pj, long time) throws InstantiationException, IllegalAccessException {
		//获取方法签名
		MethodSignature ms = (MethodSignature) pj.getSignature();
		//获取目标方法对象
		Method m = ms.getMethod();
		//获取目标对象
		Class<?> classTarget = pj.getTarget().getClass();
		//获取参数类型集合
		Class<?>[] param = ms.getParameterTypes();
		//获取目标方法
		Method targetMethod=null;
		try {
			targetMethod= classTarget.getMethod(m.getName(), param);
		} catch (Exception e) {
			e.printStackTrace();
			//throw new ServiceException(e.getMessage());
		}
		SysLog sysLog = new SysLog();
		//获取目标方法上的注解
		RequestLog requestlog =targetMethod.getAnnotation(RequestLog.class);
		if(requestlog!=null){
			sysLog.setOperation(requestlog.value());
		}
		//获取目标对象的名字
		String className =classTarget.getName();
		//获取方法对象的名字
		String methodName =ms.getName();
		sysLog.setMethod(className+"."+methodName);
		//请求的参数
		Object[] args =pj.getArgs();
		try {
			String params =new ObjectMapper().writeValueAsString(args[0]);
			sysLog.setParams(params);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//设置Ip地址
		sysLog.setIp(IPUtils.getIpAddr());
		//用户名
		String username = (String)SecurityUtils.getSubject().getSession().getAttribute("username");
//		String username = (String)SecurityUtils.getSubject().getPrincipal();
		System.out.println(username);
		sysLog.setUsername(username);
		sysLog.setTime(time);
		sysLog.setCreatedTime(new Date());
		//保存系统日志
		sysLogDao.insertObject(sysLog);
	}
	
}
